﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Configuration;
using System.Data.SqlClient;

namespace CivilleWebRole
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (TasksDDL.Items.Count == 0)
            {
                TasksDDL.Visible = false;
                QRCode.Visible = false;
            }
            else
            {
                ScriptManager scriptmanager = ScriptManager.GetCurrent(this);
                scriptmanager.RegisterAsyncPostBackControl(TasksDDL);
                if (Page.IsPostBack)
                {
                    QRCode.ImageUrl = "~/QRCodeImage.aspx?id=" + TasksDDL.SelectedValue;
                }
            }
        }

        protected void GetQRCode(object sender, EventArgs e)
        {
            QRCode.ImageUrl = "~/QRCodeImage.aspx?id=" + TasksDDL.SelectedValue;
        }

        protected void GenerateQRCodes(object sender, EventArgs e)
        {
            if (TasksDDL.SelectedItem == null)
            {
                return;
            }

            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "SELECT COUNT(*) FROM [QRCode] WHERE [TaskID] = '" + TasksDDL.SelectedItem.Value + "' AND [Status] = 'true'";
            connection.Open();
            int QRCodesNumber = (int)command.ExecuteScalar();
            
            if (QRCodesNumber < 20)
            {
                QRCodeGenerator generator = new QRCodeGenerator();
                for (int i = 0; i < 20 - QRCodesNumber; i++)
                {
                    String code = generator.generateRandomString();
                    SqlCommand createQRCodescommand = connection.CreateCommand();
                    createQRCodescommand.CommandText = "INSERT INTO [QRCode] ([Code], [Status], [TaskID]) VALUES ('" + code + "', 'true', '" + TasksDDL.SelectedItem.Value + "')";
                    createQRCodescommand.ExecuteNonQuery();
                }
            }

            connection.Close();
        }
    }
}
